import { createStore } from 'vuex'
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    cartList:[], // 购物车的数据
  },
  getters:{
    allPrice(state){ // 订单的总价
      let price = 0;
      state.cartList.forEach(item => {
        if (item.order){
           price+=item.price*item.buyNum
        }
      })
      return price
    }
  },
  mutations: {
    saveCart(state,val){ // 购物车数据的添加
      let index = state.cartList.findIndex(item => item.id == val.id && item.ties == val.ties);
      if (index>-1){
        state.cartList[index].buyNum += val.buyNum;
        return
      }
      state.cartList.push(val);
    },
    allCheck(state,bool){ // 全选
      state.cartList.forEach(item => {
        item.check = bool
      })
    },
    delect(state,i){ // 单个删除
      state.cartList.splice(i,1);
    },
    remove(state){ // 批量删除
      state.cartList = state.cartList.filter(item => item.check == false)
    },
    addOrder(state){ // 提交订单
      state.cartList.forEach(item => {
        if (item.check){
          item.order = true
        }
      })
    },
    kong(){

    },
    clearCart(state){ // 清除变成订单的购车车数据
      state.cartList = state.cartList.filter(item => item.order == false)
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    new persist({
      storage: window.localStorage,
    }),
  ]
})
